package com.example.blue;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.widget.Toolbar;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int REQUEST_ENABLE_BT = 1;
    private static final int REQUEST_PERMISSION = 2;
    private BluetoothAdapter bluetoothAdapter;
    private ArrayList<BluetoothDevice> deviceList = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    private Handler handler = new Handler(Looper.getMainLooper());
    private static final int STORAGE_PERMISSION_CODE = 1001;
    private boolean isReceiverRegistered = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false); // 隐藏默认标题

        checkPermissionsAndStartDiscovery();

        ListView listView = findViewById(R.id.device_list_view);
        Button scanButton = findViewById(R.id.add_device_btn);

        File magFile = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "mag1.txt");
        File accFile = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "AccGyro1.txt");
        File matFile = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS), "modelPara.mat");
        utils.copyAssetToFile(this, "modelPara.mat", matFile);
        if(!magFile.exists()){
            Log.d(TAG, "onCreate: magFile" + magFile.getAbsolutePath());
            utils.copyAssetToFile(this, "mag1.txt", magFile);
        }
        else{
            Log.d(TAG, "NoooooooooCreate: ");
        }

        if(!accFile.exists()){
            Log.d(TAG, "onCreate: magFile" + magFile.getAbsolutePath());
            utils.copyAssetToFile(this, "AccGyro1.txt", accFile);
        }

        if(!Python.isStarted()){
            Python.start(new AndroidPlatform(this));
            System.out.println("Python started");
        }
        // 获取蓝牙适配器
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 检查蓝牙是否可用
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 注册广播接收器
        registerBleReceiver();

        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Handle the button click event here
                startScanDevice();
            }
        });
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
        listView.setAdapter(adapter);



        // 设置列表项点击监听器，用于连接设备
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device = deviceList.get(position);
                Intent intent = new Intent(MainActivity.this, BindActivity.class);
                System.out.println("main----------------------------------------------");
                System.out.println(device.getAddress());
                intent.putExtra("DEVICE_ADDRESS", device.getAddress());
                SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.clear(); // 清空所有数据
                editor.putString("deviceId", device.getAddress());
                editor.apply();
                startActivity(intent);
            }
        });


        startScanDevice();
    }
    private void registerBleReceiver() {
        if (!isReceiverRegistered) {
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothDevice.ACTION_FOUND);
            filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(receiver, filter);
            isReceiverRegistered = true;
        }
    }

    private void unregisterBleReceiver() {
        if (isReceiverRegistered) {
            unregisterReceiver(receiver);
            isReceiverRegistered = false;
        }
    }
    // 检查权限
    private boolean checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for(int i=0;i<grantResults.length;i++) {
            System.out.println("main------grantResults[0]:" + grantResults[i]);
        }
        for(int i=0;i<permissions.length;i++) {
            System.out.println("main------permissions[0]:" + permissions[i]);
        }
        if (requestCode == STORAGE_PERMISSION_CODE) {
           for(int i=0;i<permissions.length;i++){
               if(permissions[i]=="android.permission.WRITE_EXTERNAL_STORAGE"){
                    if(grantResults[i]==-1){
                        Toast.makeText(MainActivity.this,"存储文件权限未获取",Toast.LENGTH_SHORT).show();
                    }
               }
           }
        }
    }
    private void startScanDevice() {
        // Handle the button click event here
        Toast.makeText(this, "正在扫描蓝牙设备", Toast.LENGTH_SHORT).show();
        if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        startDiscovery();
        // Add your scanning logic here
    }
    private void checkPermissionsAndStartDiscovery() {
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissions = new String[]{
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.BLUETOOTH_ADVERTISE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
        } else {
            permissions = new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION
            };
        }
        if (!Environment.isExternalStorageManager()) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }
        List<String> permissionsToRequest = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionsToRequest.add(permission);
            }
        }

        if (!permissionsToRequest.isEmpty()) {
            ActivityCompat.requestPermissions(this,
                    permissionsToRequest.toArray(new String[0]),
                    REQUEST_PERMISSION);
        } else {
            startDiscovery();
        }
    }
    private void startDiscovery() {
         bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter == null) {
            Log.e("Bluetooth", "设备不支持蓝牙");
            return;
        }
        registerBleReceiver();

        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            return;
        }
// 清空旧数据
        deviceList.clear();
        if(adapter!=null){
            adapter.clear();
            adapter.notifyDataSetChanged();
        }
        boolean started = bluetoothAdapter.startDiscovery();
        Log.d("Bluetooth", "startDiscovery: " + started);
    }
//    private void startDiscovery() {
//        if (!bluetoothAdapter.isEnabled()) {
//            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
//        } else {
//            // 清空旧数据
//            deviceList.clear();
//            adapter.clear();
//            adapter.notifyDataSetChanged();
//
//            // 启动扫描
//            statusTextView.setText("正在扫描...");
//            bluetoothAdapter.startDiscovery();
//        }
//    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            System.out.println("BroadcastReceiver:"+action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null) {
                    // 获取设备名称和 MAC 地址
                    String deviceName = device.getName();
                    String deviceHardwareAddress = device.getAddress();
                    String info = (deviceName != null ? deviceName : "未知设备") + " (" + deviceHardwareAddress + ")";
                    Log.d(TAG, "找到设备：" + info);
                    // 检查设备是否已存在于列表中，避免重复添加
                    boolean isDeviceAlreadyAdded = false;
                    for (BluetoothDevice d : deviceList) {
                        if (d.getAddress().equals(device.getAddress())) {
                            isDeviceAlreadyAdded = true;
                            break;
                        }
                    }
                    if (!isDeviceAlreadyAdded) {
                        deviceList.add(device);
                        adapter.add(info);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == Activity.RESULT_OK) {
                startDiscovery();
            } else {
                Toast.makeText(this, "蓝牙未开启，无法扫描", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 取消注册广播接收器
      unregisterBleReceiver();
      // 如果扫描正在进行，停止它
        if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消注册广播接收器
        unregisterBleReceiver();
        // 如果扫描正在进行，停止它
        if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }

    }
}
